//
//  PhotoViewController.m
//  FunOCR
//
//  Created by Luke Du on 10/03/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "PhotoViewController.h"
#import "GooOcr.h"

#import "FunOCRAppDelegate.h"

#import "TextEditingViewController.h"

#import "GDataEntrySpreadsheetDoc.h"

#import "WBImage.h"


#define M_PI   3.14159265358979323846264338327950288   /* pi */

#define DEGREES_TO_RADIANS(angle) ((angle / 180.0) * M_PI)

#define DEGREES 90.0


@interface PhotoViewController (PrivateMethods)
- (void) prepareToOcr;
- (void) finishedOcr;
@end


@implementation PhotoViewController

@synthesize ivPhotoView; 
@synthesize btnRetakePhoto; 
@synthesize btnRotate; 
@synthesize bbiBack;
@synthesize bbiSend; 

@synthesize image;

@synthesize spinner;






- (void)dealloc {
	[ivPhotoView release];
	
	[btnRetakePhoto release];
	
	[btnRotate release];
	
	[bbiBack release];
	
	[bbiSend release];
	
	[spinner release];
	
	[image release];
	
    [super dealloc];
}





// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	
	appDelegate = (FunOCRAppDelegate *)[[UIApplication sharedApplication] delegate];
	
	NSLog(@"%@", image);
	
	
	UIImage *img = [self grayscaleImage:image];
	
	
	ivPhotoView.contentMode = UIViewContentModeScaleAspectFit;
	
	ivPhotoView.image = img;
	
	
	CGRect screen = [[UIScreen mainScreen] bounds];
	
	ivPhotoView.center = CGPointMake(screen.size.width/2, screen.size.height/2);
	
	angle = DEGREES;
	


}





- (IBAction)rotateImage:(id)sender{
	
	
	rotatedImage = [ivPhotoView.image rotate:UIImageOrientationRight];
	ivPhotoView.image=rotatedImage;
	
	
}




- (IBAction)backClicked:(id)sender{
	
	NSLog(@"backClicked");
	
	[self dismissModalViewControllerAnimated:YES];
}






- (IBAction)sendClicked:(id)sender{
	
	NSLog(@"sendClicked");
	
	
	
	
	
	[self ocrAction];
	
	//[self performSelectorInBackground:@selector(ocrAction) withObject:nil];
	
}






-(void)ocrAction{
	
	if ([appDelegate isServerReachable]) {
		
		[self performSelectorInBackground:@selector(prepareToOcr) withObject:nil];
		
		
		NSDate *now = [NSDate date];
		
		NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
		
		
		[dateFormatter setDateFormat:@"yyyy-MM-dd_HH:mm:ss"];
		
		NSString *dateString = [dateFormatter stringFromDate:now];
		
		
		NSString *docName = [NSString stringWithFormat:@"OCR_Doc_%@", dateString];
		
		
		NSLog(@"now is %@", docName);
		
		
		
		GooOcr *go = [[GooOcr alloc] init];
		
		[go setDelegate:self];
		
		[go uploadImage:[self ivPhotoView].image AndName:docName];
		[go release];
	}
	else {
		
		NSLog(@"No Internet Connection");
		
		UIAlertView *alert = [[UIAlertView alloc] 
							  initWithTitle:@"Network Connection Error" 
							  message:@"You need to be connected to the internet to use this feature." 
							  delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
		[alert show];
		[alert release];
	}
}





- (UIImage *) grayscaleImage: (UIImage *) givenImage 
{ 
	
	if (givenImage.imageOrientation == UIImageOrientationUp) {
		NSLog(@"UIImageOrientationUp");
	}else if (givenImage.imageOrientation == UIImageOrientationDown) {
		NSLog(@"UIImageOrientationDown");
	}else if (givenImage.imageOrientation == UIImageOrientationLeft) {
		NSLog(@"UIImageOrientationLeft");
	}else if (givenImage.imageOrientation == UIImageOrientationRight) {
		NSLog(@"UIImageOrientationRight");
	}else if (givenImage.imageOrientation == UIImageOrientationUpMirrored) {
		NSLog(@"UIImageOrientationUpMirrored");
	}
	
	
	CGSize size = givenImage.size; 
	CGRect rect = CGRectMake(0.0f, 0.0f, size.width, size.height); 
	// Create a mono/gray color space 
	CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray(); 
	CGContextRef context = CGBitmapContextCreate(nil, size.width, 
												 size.height, 8, 0, colorSpace, kCGImageAlphaNone); 
	
	//CGContextTranslateCTM(context, image.size.width, 0);
	CGColorSpaceRelease(colorSpace); 
	// Draw the image into the grayscale context 
	CGContextDrawImage(context, rect, [givenImage CGImage]); 
	CGImageRef grayscale = CGBitmapContextCreateImage(context); 
	CGContextRelease(context); 
	// Recover the image 
	UIImage *img = [UIImage imageWithCGImage:grayscale]; 
	
	if (img.imageOrientation == UIImageOrientationUp) {
		NSLog(@"UIImageOrientationUp");
	}else if (img.imageOrientation == UIImageOrientationDown) {
		NSLog(@"UIImageOrientationDown");
	}else if (img.imageOrientation == UIImageOrientationLeft) {
		NSLog(@"UIImageOrientationLeft");
	}else if (img.imageOrientation == UIImageOrientationRight) {
		NSLog(@"UIImageOrientationRight");
	}else if (img.imageOrientation == UIImageOrientationUpMirrored) {
		NSLog(@"UIImageOrientationUpMirrored");
	}
	
	
	CFRelease(grayscale); 
	return img; 
}





// formerly saveSelectedDocumentToPath:
- (void)saveDocumentEntry:(GDataEntryDocBase *)docEntry{
	
	BOOL isSpreadsheet = [docEntry isKindOfClass:[GDataEntrySpreadsheetDoc class]];
	NSLog(@"docEntry title %@", [docEntry title]);
	if (!isSpreadsheet) {
		// in a revision entry, we've add a property above indicating if this is a
		// spreadsheet revision
		isSpreadsheet = [[docEntry propertyForKey:@"is spreadsheet"] boolValue];
	}
	
	if (isSpreadsheet) {

	} else {
		NSLog(@"not a spredsheet");
	
		
		GDataServiceGoogleDocs *docsService = [appDelegate docsService];
		[self saveDocEntry:docEntry exportFormat:@"txt" authService:docsService];
	}
}





- (void)saveDocEntry:(GDataEntryDocBase *)entry exportFormat:(NSString *)exportFormat authService:(GDataServiceGoogle *)service {
	
	// the content src attribute is used for downloading
	NSURL *exportURL = [[entry content] sourceURL];
	
	NSLog(@"exportURL :: %@", [exportURL absoluteString]);
	
	NSLog(@"entry content :: %@", [entry content]);
	
	
	if (exportURL != nil) {
		
		// we'll use GDataQuery as a convenient way to append the exportFormat
		// parameter of the docs export API to the content src URL
		GDataQuery *query = [GDataQuery queryWithFeedURL:exportURL];
		[query addCustomParameterWithName:@"exportFormat"
									value:exportFormat];
		NSURL *downloadURL = [query URL];
		
		NSLog(@"downloadURL :: %@", [downloadURL absoluteString]);
		
		// read the document's contents asynchronously from the network
		//
		
		NSLog(@"[service username] :: %@", [service username]);
		
		NSLog(@"[service password] :: %@", [service password]);
		
		
		NSURLRequest *request = [service requestForURL:downloadURL
												  ETag:nil
											httpMethod:nil];
		
		GDataHTTPFetcher *fetcher = [GDataHTTPFetcher httpFetcherWithRequest:request];
		//[fetcher setUserData:savePath];
		[fetcher beginFetchWithDelegate:self
					  didFinishSelector:@selector(fetcher:finishedWithData:)
						didFailSelector:@selector(fetcher:failedWithError:)];
	}
}





- (void)fetcher:(GDataHTTPFetcher *)fetcher finishedWithData:(NSData *)data {
	NSString *docContent = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
	NSLog(@"docContent %@",docContent);
	
	
	
	TextEditingViewController *textEditingViewController = [[TextEditingViewController alloc] initWithNibName:@"TextEditingViewController" bundle:nil];
	
	textEditingViewController.content = docContent;
	
	[self presentModalViewController:textEditingViewController animated:YES];
	
	
	
	[textEditingViewController release];
	
	
	[self finishedOcr];
}





- (void)fetcher:(GDataHTTPFetcher *)fetcher failedWithError:(NSError *)error {
	NSLog(@"Fetcher error: %@", error);
	
	[self finishedOcr];
}





- (void) serviceDidComplete
{
	NSLog(@"serviceDidComplete");
	
	if(appDelegate.currentEntry){
		NSLog(@"[appDelegate.currentEntry ETag] :: %@", [appDelegate.currentEntry ETag]);
		
		//[appDelegate.currentEntry setETag:@"*"];
		
		[self saveDocumentEntry:appDelegate.currentEntry];
	}
	
}





- (void) serviceDidFailWithError
{
	NSLog(@"serviceDidFailWithError");
	
	[self finishedOcr];
	
}





@end







@implementation PhotoViewController (PrivateMethods)

- (void) prepareToOcr{
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
	
	
	[spinner startAnimating];

}



- (void) finishedOcr{
	[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
	
	[spinner stopAnimating];

}



@end